<?php

namespace app\api\controller;

use app\api\controller\Tpmecms;
use think\Db;

/**
 * 提问
 */
class Ask extends Tpmecms
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    // public function test()
    // {
    //     $this->success('返回成功', $this->request->param());
    // }

    /**
     * 获取我提问列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_my_list($page=1,$limit=5)
    {
        $list = Db::name('ask')->where('uid',$this->auth->id)->order('time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldAskListData($val);
            }
        }

        $this->success('ok', $list);
    }

    /**
     * 发布提问
     *
     * @param string $title 发布标题
     * @param string $content 发布内容
     * @param string $images 图集
     * @return void
     */
    public function add_ask($title=null,$content=null,$images=null)
    {

        $this->IsAddAsk();//是否可以发布
        if($content || $images || $title){

            if($title)
            $this->VerifyStr($title);//验证违禁词
            if($content)
            $this->VerifyStr($content);//验证违禁词
            $data['title'] = $title;
            $data['content'] = $content;
            $data['images'] = $images;
            $data['time'] = time();
            $data['uid'] = $this->auth->id;
            $data['school_id'] = $this->auth->school_id;

            $id = Db::name('ask')->insertGetId($data);
            $this->success('发布成功',$id);
        }else{
            $this->error('请上传一些内容');
        }
    }

    /**
     * 删除我的某个提问
     *
     * @param int $id 提问id
     * @return void
     */
    public function del_ask($id)
    {
        $ask = Db::name('ask')->where('id',$id)->find();
        if(!$ask){
                $this->error('该提问不存在');
        }
        if($ask['uid']!=$this->auth->id){
            $this->error('你没有该提问');
        }
        Db::name('ask')->where('id',$id)->delete();
        $this->DelAskCommentByask_id($id);
        $this->success('删除成功');
    }



    // /**
    //  * 获取用户的信息
    //  *
    //  * @param int $uid 用户id
    //  * @return void
    //  */
    // public function get_user_data($uid)
    // {
    //     $user['user'] = Db::name('user')->where('id',$uid)->find();
    //     if(!$user['user']){
    //         $this->error('该用户不存在');
    //     }
    //     $user['follow'] = Db::name('fans')->where('fans_uid',$this->auth->id)->count();
    //     $user['fans'] = Db::name('fans')->where('uid',$this->auth->id)->count();
    //     $user['character'] = Db::name('character')->where('id','in',$user['user']['character_ids'])->column('name');//个性
    //     $user['school'] = Db::name('school')->where('id',$user['user']['school_id'])->value('name');//学校名
    //     $user['isfollow'] = $this->GetMyIsfollowUser($uid);

    //     $this->success('ok',$user);
    // }



    /**
     * 获取所有的提问列表
     *
     * @param integer $school_id 学校ID(可不传)
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_ask_list($school_id=null,$page=1,$limit=10)
    {
        $where = null;
        if($school_id)
        $where['school_id'] = $school_id;

        $list = Db::name('ask')->where($where)->order('top_switch desc,time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldAskListData($val);
            }
        }
        $this->success('ok', $list);
    }

    /**
     * 获取用户的提问列表
     *
     * @param integer $uid 用户ID
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_user_ask_list($uid,$page=1,$limit=10)
    {
        $list = Db::name('ask')->where('uid',$uid)->order('time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldAskListData($val);
            }
        }
        $this->success('ok', $list);
    }

    /**
     * 获取提问详情
     *
     * @param int $id 提问ID
     * @return void
     */
    public function get_data($id)
    {
        $val = Db::name('ask')->where('id',$id)->find();
        if($val){
            $val = $this->ChangeFieldAskData($val);
        }else{
            $this->error('该提问不存在');
        }
        $this->IncAskViews($id);
        $this->success('ok', $val);

    }

    /**
     * 删除我的评论
     *
     * @param int $id 评论id
     * @return void
     */
    public function del_me_comment($id)
    {
        $comment = Db::name('ask_comment')->where('id',$id)->where('uid',$this->auth->id)->find();
        if(!$comment){
            $this->error('该评论不存在');
        }
        $ids = [$id];
        //删除下级评论
        $xia_ids = Db::name('ask_comment')->where('top_id',$id)->column('id');
        if($xia_ids){
            $ids = array_merge($xia_ids,$ids);
            //在找下级
            $xia2_ids = Db::name('ask_comment')->where('top_id','in',$xia_ids)->column('id');
            if($xia2_ids){
                $ids = array_merge($xia2_ids,$ids);
            }
        }
        
        $res = Db::name('ask_comment')->where('id','in',$ids)->delete();
        $this->success('删除成功',$res);
    }

    /**
     * 改变提问字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldAskListData($val){
        // $val['comment'] = $this->GetAskCommentArray($val['id']);//获取提问评论列表
        $val['user'] = $this->GetUserData2($val['uid']);
        $val['m'] = date('n',$val['time']);
        $val['d'] = date('d',$val['time']);
        $val['comment_num'] = $this->GetAskCommentNum($val['id']);
        $val['self_likes'] = $this->GetUserIsAsklikes($val['id'],$this->auth->id);
        $val['date_str'] = $this->TimeToStr($val['time']);
        return $val;
    }



     /**
     * 改变提问字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldAskData($val){
        $val['comment'] = $this->GetAskCommentArray($val['id']);//获取提问评论列表
        $val['user'] = $this->GetUserData2($val['uid']);
        $val['m'] = date('n',$val['time']);
        $val['d'] = date('d',$val['time']);
        $val['comment_num'] = $this->GetAskCommentNum($val['id']);
        $val['self_likes'] = $this->GetUserIsAsklikes($val['id'],$this->auth->id);
        
        $val['date_str'] = $this->TimeToStr($val['time']);
        return $val;
    }

    /**
     * 评论提问
     *
     * @param int $ask_id 提问id
     * @param string $content 内容
     * @param string $images 图集(可不传)
     * @param int $comment_id 评论id(可不传)
     * @return void
     */
    public function add_comment($ask_id,$content=null,$comment_id=null,$images=null)
    {
        $val = Db::name('ask')->where('id',$ask_id)->find();
        if(!$val){
            $this->error('该提问不存在');
        }
        $where['ask_id'] = $ask_id;
        $this->VerifyStr($content);
        if($comment_id){

            $res = Db::name('ask_comment')->where('id',$comment_id)->where($where)->find();
            if(!$res){
                $this->error('该评论不存在');
            }
            if($res['comment_id']>0){
                $where['top_id'] = $res['top_id'];
            }else{
                $where['top_id'] = $comment_id;
            }
            $where['comment_uid'] = $res['uid'];//被评论的用户id
        }
        $where['comment_id'] = $comment_id;
       
        $where['content'] = $content;
        $where['images'] = $images;
        $where['uid'] = $this->auth->id;
        $where['time'] = time();     

        $id = Db::name('ask_comment')->insertGetId($where);


        // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
        // $this->AddMsg($val['uid'],4,$ask_id,$this->auth->id,$this->auth->nickname.'给您的提问回复了');

        if($comment_id){
            if($res['uid']!=$this->auth->id)//自己评论自己不添加
            $this->AddMsg($res['uid'],4,$ask_id,$this->auth->id,$this->auth->nickname.'给你提问评论回复了');
        }else{
            if($val['uid']!=$this->auth->id)//自己评论自己不添加
            $this->AddMsg($val['uid'],4,$ask_id,$this->auth->id,$this->auth->nickname.'给你提问回复了');
        }

        $this->success('评论成功', $id);
    }


    
    /**
     * 修改点赞
     *
     * @param int $ask_id 提问id
     * @param int $comment_id 评论ID(可不传)
     * @return void
     */
    public function update_likes($ask_id,$comment_id=null)
    {
       
        $data['uid'] = $this->auth->id;
        $data['ask_id'] = $ask_id;
        if($comment_id)
            $data['comment_id'] = $comment_id;
        $ask = Db::name('ask')->where('id',$ask_id)->find();
        $res = Db::name('asklikes')->where($data)->find();
        if(!$res){
            $data['time'] = time();
            if(!$ask)$this->error('该提问不存在');
            // $data['ask_uid'] = $ask['uid'];
            $data['id'] = Db::name('asklikes')->insertGetId($data);
            if(!$comment_id){
                //点赞数+1
                $this->IncAskLikes($ask_id);

                // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
                $this->AddMsg($ask['uid'],3,$ask_id,$this->auth->id,$this->auth->nickname.'给你提问点赞了');
            }else{
                $comment = Db::name('ask_comment')->where('ask_id',$ask_id)->where('id',$comment_id)->find();
                // var_dump($ask_id,$comment_id);
                // halt($comment);
                $this->AddMsg($comment['uid'],3,$ask_id,$this->auth->id,$this->auth->nickname.'给你提问评论点赞了');
            }

            $this->success('点赞成功',1);
        }else{
            Db::name('asklikes')->where('id',$res['id'])->delete();
            if(!$comment_id){
            
            //点赞数-1
            $this->DecAskLikes($ask_id);

            // $this->AddMsg($ask['uid'],3,$ask_id,$this->auth->id,$this->auth->nickname.'给你提问取消点赞了');
            }else{
                $comment = Db::name('ask_comment')->where('ask_id',$ask_id)->where('id',$comment_id)->find();
                // var_dump($ask_id,$comment_id);
                // halt($comment);
                // $this->AddMsg($comment['uid'],3,$ask_id,$this->auth->id,$this->auth->nickname.'给你提问评论取消点赞了');
            }
            $this->success('取消点赞',0);
        }
    }



}
